$(function () {
    $.extend($.fn.validatebox.defaults.rules, {
        equals: {
            validator: function (value, param) {
                return value == $(param[0]).val();
            },
            message: 'Field do not match.'
        }
    });

    $.extend($.fn.validatebox.defaults.rules, {
        nonEquals: {
            validator: function (value, param) {
                return value != $(param[0]).val();
            },
            message: 'Field match.'
        }
    });

    $.extend($.fn.validatebox.defaults.rules, {
        idNoValidate: {
            validator: function (value, param) {
                //身份证的地区代码对照
                var aCity = { 11: "北京", 12: "天津", 13: "河北", 14: "山西", 15: "内蒙古", 21: "辽宁", 22: "吉林", 23: "黑龙江", 31: "上海", 32: "江苏", 33: "浙江", 34: "安徽", 35: "福建", 36: "江西", 37: "山东", 41: "河南", 42: "湖北", 43: "湖南", 44: "广东", 45: "广西", 46: "海南", 50: "重庆", 51: "四川", 52: "贵州", 53: "云南", 54: "西藏", 61: "陕西", 62: "甘肃", 63: "青海", 64: "宁夏", 65: "新疆", 71: "台湾", 81: "香港", 82: "澳门", 91: "国外" };
                //获取证件号码
                var person_id = value;
                //合法性验证
                var sum = 0;
                //出生日期
                var birthday;
                //验证长度与格式规范性的正则
                var pattern = new RegExp(/(^\d{15}$)|(^\d{17}(\d|x|X)$)/i);
                if (pattern.exec(person_id)) {
                    //验证身份证的合法性的正则
                    pattern = new RegExp(/^[1-9]\d{7}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])\d{3}$/);
                    if (pattern.exec(person_id)) {
                        //获取15位证件号中的出生日期并转位正常日期
                        birthday = "19" + person_id.substring(6, 8) + "-" + person_id.substring(8, 10) + "-" + person_id.substring(10, 12);
                    }
                    else {
                        person_id = person_id.replace(/x|X$/i, "a");
                        //获取18位证件号中的出生日期
                        birthday = person_id.substring(6, 10) + "-" + person_id.substring(10, 12) + "-" + person_id.substring(12, 14);

                        //校验18位身份证号码的合法性
                        for (var i = 17; i >= 0; i--) {
                            sum += (Math.pow(2, i) % 11) * parseInt(person_id.charAt(17 - i), 11);
                        }
                        if (sum % 11 != 1) {
                            return false;
                        }
                    }
                    //检测证件地区的合法性
                    if (aCity[parseInt(person_id.substring(0, 2))] == null) {
                        return false;
                    }
                    var dateStr = new Date(birthday.replace(/-/g, "/"));

                    if (birthday != (dateStr.getFullYear() + "-" + Append_zore(dateStr.getMonth() + 1) + "-" + Append_zore(dateStr.getDate()))) {
                        return false;
                    }
                }
                else {
                    return false;
                }
                return true;
            },
            message: ''
        }
    });

    $("#userInfo").click(function () {
        initComobox($('#sex'), sex);
        initComobox($('#nation'), nation);
        var userType = $("#userTypeInput").val();
        var url = "";
        if (userType == 1) {
            url = "student/idno/" + $("#userIdNo").val();
        } else {
            url = "teacher/idno/" + $("#userIdNo").val();
            $('#picture').bind('change', pictureChange);
        }
        if (userType != 0) {
            $('#modifyInfoDialog').dialog("open");
            $.ajax({
                    type: "GET",
                    url: url,
                    dataType: "json",
                    cache: false,
                    success: function (data) {
                        data.nation = data.nation - 1;
                        $("#modifyInfoForm").form("load", data);
                        $("#nopicture").css("display", "none");
                        var tempUrl = addTimestampToURL('teacher/getTeacherPicture/' + data.id);
                        $("#picturepreview").html("<img src='" + tempUrl + "' width=150 height=150 />");
                    }
                }
            );
        }
    });

    $("#modify_info_submit").click(function () {
        var userType = $("#userTypeInput").val();
        var url = "";
        if (userType == 1) {
            url = "student/update";
        } else {
            url = "teacher/update";
        }
        if ($("#modifyInfoForm").form('validate')) {
            $("#nation").combobox('select', parseInt($("#nation").combobox('getValue')) + 1);
            $("#modifyInfoForm").form('submit',
                {
                    url: url,
                    success: function (data) {
                        var data = eval('(' + data + ')');
                        if (data.result) {
                            $("#modifyInfoDialog").dialog("close");
                            $.messager.alert("提示", "信息更新成功！");
                        }
                    }
                });
        } else {
            $.messager.alert("错误", "无可提交的有效信息，请检查您的输入！", "error");
        }
    });

    $("#modify_pass_submit").click(function () {
        if ($("#opwd").validatebox("isValid")
            && $("#pwd").validatebox("isValid")
            && $("#npwd").validatebox("isValid")) {
            $("#modify_pass_form").form('submit',
                {
                    url: 'authentication/password/modify',
                    onSubmit: function () {
                    },
                    success: function (data) {
                        var data = eval('(' + data + ')');
                        if (data) {
                            $("#modify_pass_dlg").dialog("close");
                            $.messager.alert("提示", "密码修改成功！");
                        }
                    }
                });
        } else {
            $.messager.alert("错误", "无可提交的有效信息，请检查您的输入！", "error");
        }
    });

    $("#modify_pass").click(function () {
        $("#opwd").val("");
        $("#pwd").val("");
        $("#npwd").val("");
        $("#modify_pass_dlg").dialog("open");
    });

    $("#param_config_submit").click(function () {
        $("#param_config_form").form("submit", {
            url: 'param/update',
            onSubmit: function () {
            },
            success: function (data) {
                if (data) {
                    $("#param_config_dlg").dialog("close");
                    $.messager.alert("提示", "系统参数修改成功！");
                }
            }
        });
    });

    //绑定功能树单击事件
    $(".easyui-tree").tree({onClick: tree_click});

    //处理树单击事件
    function tree_click(node) {
        if ($('#center_tabs').tabs('exists', node.text)) {
            $('#center_tabs').tabs('select', node.text);
        } else {
            if (node.attributes.url == "param") {
                $("#param_config_dlg").dialog("open");
                $("#param_config_form").form("load", "param/list");
            } else {
                var options = {title: node.text, selected: true, closable: true};
                if (node.attributes.url == "temp") {
                    options = $.extend(options, {content: "正在建设中..."});
                } else {
                    options = $.extend(options, {content: createFrame(node.attributes.url)});
                    //options = $.extend(options, {href: node.attributes.url})
                }
                $('#center_tabs').tabs('add', options);
            }

        }
    }
});
function createFrame(url) {
    var s = '<iframe scrolling="auto" frameborder="0"  src="' + url + '" style="width:100%;height:100%;"></iframe>';
    return s;
}

function Append_zore(temp) {
    if (temp < 10) {
        return "0" + temp;
    }
    else {
        return temp;
    }
}

function pictureChange() {
    if (!validUploadJpgFile()) {
        return;
    }
    var sessionId = $.cookie('JSESSIONID');
    $('#pictureForm').form({
        url: 'teacher/' + sessionId + '/picture',
        error: function (jqXHR, textStatus, errorThrown) {
            $.messager.alert("操作提示", "数据保存异常:[" + jqXHR.statusText + "]", "error");
        },
        success: function (data) {
            var fileName = $('#picture').val();
            var suffix = fileName.substring(fileName.lastIndexOf("."), fileName.length);
            $("#picturepreview").html("");
            $("#nopicture").css("display", "none");
            var tempUrl = addTimestampToURL('upload/' + sessionId + suffix);
            $("#picturepreview").html("<img src='" + tempUrl + "' width=150 height=150 />");
        }
    });
    //提交表单
    $('#pictureForm').submit();
}
